import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class IrisDataset {
    private double[][] features;
    private String[] labels;
    private String[] targetNames;

    public IrisDataset() {
        this.targetNames = new String[]{"setosa", "versicolor", "virginica"};
        loadData();
    }

    private void loadData() {
        List<double[]> featureList = new ArrayList<>();
        List<String> labelList = new ArrayList<>();

        try (BufferedReader br = new BufferedReader(new FileReader("C:/Users/redmi/IdeaProjects/PCA/src/iris.txt"))) {
            String line;
            while ((line = br.readLine()) != null && !line.trim().isEmpty()) {
                String[] parts = line.split(",");
                if (parts.length == 5) {
                    double[] features = new double[4];
                    for (int i = 0; i < 4; i++) {
                        features[i] = Double.parseDouble(parts[i]);
                    }
                    featureList.add(features);
                    labelList.add(parts[4]);
                }
            }
        } catch (IOException e) {
            // 如果文件不存在，使用内置数据
            System.out.println("未找到iris.txt文件，使用内置数据...");
            useBuiltinData(featureList, labelList);
        }

        this.features = featureList.toArray(new double[0][]);
        this.labels = labelList.toArray(new String[0]);
    }

    private void useBuiltinData(List<double[]> featureList, List<String> labelList) {
        // 内置的鸢尾花数据集样本数据
        double[][] builtinFeatures = {
                {5.1, 3.5, 1.4, 0.2}, {4.9, 3.0, 1.4, 0.2}, {4.7, 3.2, 1.3, 0.2},
                {7.0, 3.2, 4.7, 1.4}, {6.4, 3.2, 4.5, 1.5}, {6.9, 3.1, 4.9, 1.5},
                {6.3, 3.3, 6.0, 2.5}, {5.8, 2.7, 5.1, 1.9}, {7.1, 3.0, 5.9, 2.1}
        };

        String[] builtinLabels = {
                "Iris-setosa", "Iris-setosa", "Iris-setosa",
                "Iris-versicolor", "Iris-versicolor", "Iris-versicolor",
                "Iris-virginica", "Iris-virginica", "Iris-virginica"
        };

        for (int i = 0; i < builtinFeatures.length; i++) {
            featureList.add(builtinFeatures[i]);
            labelList.add(builtinLabels[i]);
        }
    }

    public double[][] getFeatures() {
        return features;
    }

    public String[] getLabels() {
        return labels;
    }

    public String[] getTargetNames() {
        return targetNames;
    }
}